package com.hengxinguotong.zhihuichengjian.ui.engineering.reservation;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.ReservationAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Menu;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.Reservation;
import com.hengxinguotong.zhihuichengjian.bean.ReservationListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectMenuPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 塔吊升降机的任务预约
 * Created by liux on 2017/4/1.
 */

public class ReservationListActivity extends BaseActivity {

    private static final String TAG = "ReservationList";
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.reservation_lv)
    PullToRefreshListView reservationLv;
    @BindView(R.id.add)
    HXTextView add;
    private ReservationAdapter reservationAdapter;
    private SelectMenuPop selectMenuPop;
    private static final int UPDATE = 1001;
    private static final int HISTORY = 1002;
    private int equipmentType = 1;
    private boolean isHistory = false;
    private int pageIndex = 1;
    private List<Reservation> reservations;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE:
                    List<Reservation> datas = (List<Reservation>) msg.obj;
                    addReservationList(datas);
                    break;
                case HISTORY:
                    List<Reservation> hostpryDatas = (List<Reservation>) msg.obj;
                    addData(hostpryDatas);
                    break;
            }
        }
    };
    private List<MenuBean> menuList;//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reservationlist);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        add.setVisibility(View.VISIBLE);
        if (hasAdd()) {
            add.setText("操作");
        } else {
            add.setText("历史预约");
        }
        equipmentType = getIntent().getIntExtra("equipmentType", 1);
        isHistory = getIntent().getBooleanExtra("isHistory", false);
        reservations = new ArrayList<>();
        reservationAdapter = new ReservationAdapter(ReservationListActivity.this, reservations);
        reservationLv.setAdapter(reservationAdapter);
        reservationLv.setMode(PullToRefreshBase.Mode.BOTH);
        reservationLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                if (isHistory) {
                    getReservationHistoryList(null);
                } else {
                    getReservationList(null);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(isHistory){
                    getReservationHistoryList(null);
                }else{
                    getReservationList(null);
                }
            }
        });

        reservationLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ReservationListActivity.this, AddReservationActivity.class);
                intent.putExtra("reservation", reservationAdapter.getItem(position - 1));
                if (isHistory) {
                    intent.putExtra("isOnlyRead", true);
                }
                startActivityForResult(intent, UPDATE);
            }
        });

        if (isHistory) {
            getReservationHistoryList(getResources().getString(R.string.loading));
            add.setVisibility(View.GONE);
            if (equipmentType == 1) {
                titleTv.setText("塔吊历史列表");
            } else {
                titleTv.setText("升降机历史列表");
            }
        } else {
            if (equipmentType == 1) {
                titleTv.setText("塔吊预约列表");
            } else {
                titleTv.setText("升降机预约列表");
            }
        }
        handler.postDelayed(MyRunnable, 500);

        String authority = SPUtil.getString(this, "authority");
        if(!Utils.isEmpty(authority)){
            try{
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                menuList = menuListRes.getValue();
            }catch (Exception e){
                Log.e(TAG, e.getMessage().toString());
            }
        }
        if(menuList == null){
            menuList = new ArrayList<>();
        }
        if (equipmentType == 1) {
            for (MenuBean menu:menuList){
                if(menu.getId() == 800){
                    menu.setHasNew(false);
                    for(MenuBean sMenu:menu.getData()){
                        if(sMenu.getId() == 820){
                            sMenu.setHasNew(false);
                        }
                    }
                }
            }
        }else {
            for (MenuBean menu:menuList){
                if(menu.getId() == 800){
                    menu.setHasNew(false);
                    for(MenuBean sMenu:menu.getData()){
                        if(sMenu.getId() == 830){
                            sMenu.setHasNew(false);
                        }
                    }
                }
            }
        }
        MenuListRes res = new MenuListRes();
        res.setValue(menuList);
        authority = new Gson().toJson(res);
        SPUtil.put(this, "authority", authority);
    }

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                setResult(0);
                finish();
                break;
            case R.id.add:
                if (hasAdd()) {
                    showSelectMenuPop();
                } else {
                    Intent intent = new Intent(ReservationListActivity.this, ReservationListActivity.class);
                    intent.putExtra("isHistory", true);
                    intent.putExtra("equipmentType", equipmentType);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            setResult(0);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            reservationLv.setRefreshing();
        }
    };

    private void getReservationList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            if(!isHistory){
                jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            }
            jsonObject.put("appointmentId", SPUtil.getString(this, "userId"));
            jsonObject.put("equipmentType", equipmentType);
            jsonObject.put("pageNum", pageIndex);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/taskAppointment/queryList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (reservationLv.isRefreshing()) {
                    reservationLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ReservationListRes reservationListRes = gson.fromJson(json, ReservationListRes.class);
                    Message msg = handler.obtainMessage();
                    msg.what = UPDATE;
                    msg.obj = reservationListRes.getValue();
                    msg.sendToTarget();
                }
            }

            @Override
            public void onFailure(String json) {
                if (reservationLv.isRefreshing()) {
                    reservationLv.onRefreshComplete();
                }
            }
        });
    }

    private void addReservationList(List<Reservation> datas){
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(reservationLv);
            }else{
                dismissEmptyView();
            }
            reservations = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                reservationLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            reservations.addAll(datas);
        }
        reservationAdapter.setDatas(reservations);
        if (datas.size() < Utils.ONCECOUNT) {
            reservationLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
        updateTopIcon(reservations);
    }


    private void getReservationHistoryList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("appointmentId", SPUtil.getString(this, "userId"));
            jsonObject.put("equipmentType", equipmentType);
            jsonObject.put("pageNum", pageIndex);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/taskAppointment/queryAllList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (reservationLv.isRefreshing()) {
                    reservationLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ReservationListRes reservationListRes = gson.fromJson(json, ReservationListRes.class);
//                    addData(reservationListRes.getValue());
                    Message msg = handler.obtainMessage();
                    msg.what = UPDATE;
                    msg.obj = reservationListRes.getValue();
                    msg.sendToTarget();
                }
            }

            @Override
            public void onFailure(String json) {
                if (reservationLv.isRefreshing()) {
                    reservationLv.onRefreshComplete();
                }
            }
        });
    }

    private void updateTopIcon(List<Reservation> reservations) {
        boolean hasUrgentTask = false;
        for (Reservation reservation : reservations
                ) {
            if (reservation.getIsUrgentTask() == 1) {
                hasUrgentTask = true;
                break;
            }
        }

    }

    private void showSelectMenuPop() {
        List<Menu> menus = new ArrayList<Menu>();
        Menu menu1 = new Menu();
        menu1.setIcon(R.mipmap.icon_add);
        menu1.setTitle("新增任务");
        menus.add(menu1);


        Menu menu2 = new Menu();
        menu2.setIcon(R.mipmap.create_time);
        menu2.setTitle("历史任务");
        menus.add(menu2);

        selectMenuPop = new SelectMenuPop(this, menus, new SelectMenuPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                Intent intent;
                switch (position) {
                    case 0:
                        intent = new Intent(ReservationListActivity.this, AddReservationActivity.class);
                        intent.putExtra("equipmentType", equipmentType);
                        startActivityForResult(intent, UPDATE);
                        break;
                    case 1:
                        intent = new Intent(ReservationListActivity.this, ReservationListActivity.class);
                        intent.putExtra("isHistory", true);
                        intent.putExtra("equipmentType", equipmentType);
                        startActivity(intent);
                        break;
                }
            }
        });
        selectMenuPop.setFocusable(true);
        selectMenuPop.setOutsideTouchable(true);
        selectMenuPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        selectMenuPop.update();
        selectMenuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (selectMenuPop.isShowing()) {
            selectMenuPop.dismiss();
        } else {
            selectMenuPop.showAsDropDown(add);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UPDATE) {
            handler.postDelayed(MyRunnable, 500);
        }
    }


    private void addData(List<Reservation> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(reservationLv);
            }else{
                dismissEmptyView();
            }
            reservations = datas;
            reservationAdapter = new ReservationAdapter(this, reservations);
            reservationLv.setAdapter(reservationAdapter);
            reservationAdapter.notifyDataSetChanged();
            if (datas.size() == Utils.ONCECOUNT) {
                reservationLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            reservations.addAll(datas);
            reservationAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            reservationLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
        updateTopIcon(reservations);
    }


    //    private DragSortListView.DropListener onDrop =
//            new DragSortListView.DropListener() {
//                @Override
//                public void drop(int from, int to) {
//                    if (from != to) {
//                        Task item = taskAdapter.getItem(from);
//                        taskAdapter.remove(from);
//                        taskAdapter.insert(item, to);
//                        reservationLv.moveCheckState(from, to);
//                        Log.d("DSLV", "Selected item is " + reservationLv.getCheckedItemPosition());
//                    }
//                }
//            };
}
